<?php
$param = [
    'money'=>'定投金额',
    'income'=>'单次利率',
    'expected'=>'目标金额',
    'all'=>'存款',
];
//echo "<pre>";
//var_dump($param);
$money = isset($_GET['money'])?$_GET['money']: 10;
$income = isset($_GET['income'])?$_GET['income']: 0.05;
$expected = isset($_GET['expected'])?$_GET['expected']: 20000;
//$income= $_GET['income'] or 0.05;
//$expected = $_GET['expected'] or 20000;

$a= 0;
$all = $_GET['all'];
//$income = $income/12;
$y = $m = 1;
$i= 1;
$draw = [];
$all_lixi = 0;
echo "<pre>";
do{
    $list = [];
    $lixi = round($all*$income,2);
    $all = round($all*(1+$income) + $money,2);
//    $a += $money;
    $list['day'] = "第 $i 月";
    $list['all'] = $all;
    $list['all_money'] += isset($draw[$i-1])?$draw[$i-1]['all_money']+$money:$money;
    $list['lixi'] = $lixi;
	$list['all_lixi'] += isset($draw[$i-1])?$draw[$i-1]['all_lixi']+$lixi:$lixi;;
//	echo "第{$i}天。 总资金:{$all}元\t总投入:{$a}\t总利息为{$all_lixi}\t本次定投金额为:{$money}\t昨日利息为:{$lixi}".PHP_EOL;
	echo "第{$i}天。 总资金:{$all}元\t总投入:{$list['all_money']}\t总利息为{$list['all_lixi']}\t本次定投金额为:{$money}\t昨日利息为:{$lixi}".PHP_EOL;
	$draw[$i] = $list;
    $i ++;
}while($all <= $expected);

 function downloadCsv($headlist = array(), $data = array(), $fileName)
{

    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');
    header('Cache-Control: max-age=0');

    //打开PHP文件句柄,php://output 表示直接输出到浏览器
    $fp = fopen('php://output', 'a');

    //输出Excel列名信息
    foreach ($headlist as $key => $value) {
        //CSV的Excel支持GBK编码，一定要转换，否则乱码
        $headlist[$key] = iconv('utf-8', 'gbk', $value);
    }

    //将数据通过fputcsv写到文件句柄
    fputcsv($fp, $headlist);

    //计数器
    $num = 0;

    //每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
    $limit = 100000;

    //逐行取出数据，不浪费内存
    $count = count($data);
    for ($i = 0; $i < $count; $i++) {

        $num++;

        //刷新一下输出buffer，防止由于数据过多造成问题
        if ($limit == $num) {
            ob_flush();
            flush();
            $num = 0;
        }

        $row = $data[$i];
        foreach ($row as $key => $value) {
            $value = iconv('utf-8', 'gbk', $value);
            $row[$key] = '="' . $value . '"';
        }

        fputcsv($fp, $row);
    }
    die();
}

if(isset($_GET['download'])){
    $headlist = ['天数','余额','总投入','昨日利息','总利息'];
    downloadCsv($headlist,$draw,'定投模拟器');
}else{
//    echo json_encode($draw);
}

//var_dump($draw);

